/* eslint-disable react/jsx-no-bind */
/* eslint-disable max-lines-per-function */
import React, {useState, useEffect, useCallback} from 'react';
import {withRouter} from 'react-router-dom';
import {debounce} from 'lodash';
import moment from 'moment';
import {QuestionCircleOutlined} from '@ant-design/icons';
import {Form} from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
    Button,
    Input,
    message,
    Table,
    Row,
    Col,
    DatePicker,
    Select,
    Modal,
    Popover,
} from 'antd';
import {chatRoomSearch, getDept, getChannel, chatRoomDownload, updateName} from '~/service/sales';
import {getAccountList} from '~/service/screen';
import popUpContainer from '~/utils/common/popupFix';
import './advStyl';
import format from './format';

const {RangePicker} = DatePicker;
const {Option} = Select;
const WAIT_TIME = 500;
function RoomList(props) {
    const {
        form: {
            getFieldDecorator,
            validateFields,
            setFieldsValue,
            resetFields,
        },
    } = props;
    const [department, setDepartment] = useState();
    const [depList, setDepList] = useState([]);
    const [channelList, setChannelList] = useState([]);
    const [loading, setLoading] = useState(false);
    const [searchList, setSearchList] = useState([]);
    const [editVisible, setEditVisible] = useState(false);
    const [editId, setEditId] = useState();
    const [saleName, setSaleName] = useState();
    const [nameList, setNameList] = useState([]);
    const groupHtml = (
        <span>
            群类型
            <Popover content="初高中投放尾量进的群为涓流群，其余均为正常群。" trigger="hover">
                <QuestionCircleOutlined className="leftGap" />
            </Popover>
        </span>
    );
    const columns = [
        {
            title: '学部',
            width: 120,
            dataIndex: 'department',
            key: 'department',
        },
        {
            title: '投放渠道',
            width: 100,
            dataIndex: 'channel',
            key: 'channel',
        },
        {
            title: '群名称',
            width: 200,
            dataIndex: 'chatroomName',
            key: 'chatroomName',
        },
        {
            title: '群类别',
            width: 100,
            dataIndex: 'chatroomCategoryName',
            key: 'chatroomCategoryName',
        },
        {
            title: groupHtml,
            width: 120,
            dataIndex: 'chatroomTypeName',
            key: 'chatroomTypeName',
        },
        {
            title: '销售名称',
            width: 100,
            dataIndex: 'saleName',
            key: 'saleName',
        },
        {
            title: '班级名称',
            width: 220,
            dataIndex: 'clazzName',
            key: 'clazzName',
        },
        {
            title: '班级ID',
            width: 100,
            dataIndex: 'clazzId',
            key: 'clazzId',
        },
        {
            title: '开班时间',
            width: 170,
            dataIndex: 'clazzBeginTime',
            key: 'clazzBeginTime',
            render(value) {
                return moment(value, format.dateFormat).format('YYYY-MM-DD HH:00');
            }
        },
        {
            title: '年级',
            width: 100,
            dataIndex: 'grade',
            key: 'grade',
        },
        {
            title: '科目',
            width: 100,
            dataIndex: 'subject',
            key: 'subject',
        },
        {
            title: '群主',
            width: 100,
            dataIndex: 'chatroomOwner',
            key: 'chatroomOwner',
        },
        {
            title: '计入成本',
            width: 100,
            dataIndex: 'canCost',
            key: 'canCost',
        },
        {
            title: '进群人数',
            width: 100,
            dataIndex: 'chatroomNum',
            key: 'chatroomNum',
        },
        {
            title: '退群人数',
            width: 100,
            dataIndex: 'quitUserNum',
            key: 'quitUserNum',
        },
        {
            title: '退群率',
            width: 100,
            dataIndex: 'quitUserRate',
            key: 'quitUserRate',
        },
        {
            title: '留存人数',
            width: 100,
            dataIndex: 'retainUserNum',
            key: 'retainUserNum',
        },
        {
            title: '单用户成本',
            width: 120,
            dataIndex: 'singleCost',
            key: 'singleCost',
        },
        {
            title: '群成本',
            width: 100,
            dataIndex: 'advPrice',
            key: 'advPrice',
        },
        {
            title: '操作',
            key: 'operation',
            fixed: 'right',
            width: 120,
            render(text, record) {
                return (
                    <>
                        <Button
                            size="small"
                            onClick={() => {
                                setEditId(record.id);
                                setSaleName(record.saleName);
                                setNameList([]);
                                setEditVisible(true);
                            }}
                        >
                            修改销售名
                        </Button>
                    </>
                );
            },
        },
    ];
    useEffect(() => {
        getDept().then(res => {
            setDepList(res.data.departmentList);
        });
        handleSearch();
    }, []);

    useEffect(() => {
        if (department) {
            getChannel(department).then(res => {
                setChannelList(res.data.channelList);
            });
        }
        resetFields(['channel']);
    }, [department]);

    function handleSearch(e) {
        e && e.preventDefault();
        setLoading(true);
        const param = processSearchParam();

        chatRoomSearch(param).then(res => {
            setSearchList(res.data.chatroomResulList);
            setLoading(false);
        })
            .catch(error => {
                setLoading(false);
                message.error(error.msg);
            });
    }

    // 参数处理逻辑
    function processSearchParam() {
        const param = {};
        validateFields((errObj, values) => {
            if (!errObj) {
                if (values.department) {
                    param.department = values.department;
                }
                if (values.channel) {
                    param.channel = values.channel;
                }
                // canCost 1 2
                if (values.canCost) {
                    param.canCost = values.canCost;
                }
                if (values.clazzName) {
                    param.clazzName = values.clazzName;
                }
                if (values.saleName) {
                    param.saleName = values.saleName;
                }

                if (values.clazzBeginTime && values.clazzBeginTime.length > 0) {
                    param.clazzBeginTime = [
                        values.clazzBeginTime[0].startOf('day').format('YYYY-MM-DD HH:mm'),
                        values.clazzBeginTime[1].endOf('day').format('YYYY-MM-DD HH:mm')
                    ];
                }
            }
        });

        return param;
    }

    function handleReset() {
        resetFields();
        handleSearch();
    }

    function download() {
        const param = processSearchParam();
        chatRoomDownload(param, '群明细');
    }

    function handleOk() {
        if (editId && saleName) {
            const param = {
                id: editId,
                saleName
            };
            updateName(param).then(res => {
                setEditVisible(false);
                // 重新搜索
                handleSearch();
            })
                .catch(errObj => {
                    setEditVisible(false);
                    message.error(errObj.msg);
                });
        }
    }

    function handleCancel() {
        setEditVisible(false);
    }

    // 销售修改下拉
    const nameSearch = useCallback(debounce(keyword => {
        if (keyword) {
            getAccountList({keyword}).then(res => {
                const list = res.data.map(e => e.displayName);
                setNameList(list);
            })
                .catch(errObj => {
                    message.error(errObj.msg);
                });
        }
        else {
            setNameList([]);
        }
    }, WAIT_TIME, {leading: true}), []);

    return (
        <div>
            <Form onSubmit={handleSearch}>
                <Row gutter={24} type="flex" align="bottom">
                    <Col span={8}>
                        <Form.Item label="开班日期">
                            {getFieldDecorator('clazzBeginTime', {
                                initialValues: []
                            })(
                                <RangePicker
                                    style={{
                                        width: '100%'
                                    }}
                                    showTime={false}
                                    format="YYYY-MM-DD"
                                />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item label="学部">
                            {
                                getFieldDecorator('department', {
                                    initialValues: ''
                                })(
                                    <Select
                                        placeholder="请选择学部"
                                        onChange={setDepartment}
                                        getPopupContainer={popUpContainer}
                                        allowClear
                                    >
                                        {
                                            depList.map(item => (
                                                <Option key={item} value={item} title={item}>
                                                    {item}
                                                </Option>
                                            ))
                                        }
                                    </Select>
                                )
                            }
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item label="投放渠道">
                            {
                                getFieldDecorator('channel', {
                                    initialValues: ''
                                })(
                                    <Select
                                        placeholder="请选择投放渠道"
                                        getPopupContainer={popUpContainer}
                                        allowClear
                                    >
                                        {
                                            channelList.map(item => (
                                                <Option key={item.name} value={item.name}>
                                                    {item.name}
                                                </Option>
                                            ))
                                        }
                                    </Select>
                                )
                            }
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item label="班级名称">
                            {
                                getFieldDecorator('clazzName', {
                                    initialValues: ''
                                })(
                                    <Input
                                        placeholder="请输入班级名称"
                                        allowClear
                                    />
                                )
                            }
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item label="销售名称">
                            {
                                getFieldDecorator('saleName', {
                                    initialValues: ''
                                })(
                                    <Input
                                        allowClear
                                        placeholder="请输入销售名称"
                                    />
                                )
                            }
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item label="是否计入成本">
                            {
                                getFieldDecorator('canCost', {
                                    initialValues: ''
                                })(
                                    <Select
                                        placeholder="请选择"
                                        getPopupContainer={popUpContainer}
                                        allowClear
                                    >
                                        <Option value={1}>是</Option>
                                        <Option value={2}>否</Option>
                                    </Select>
                                )
                            }
                        </Form.Item>
                    </Col>
                </Row>
                <Row>
                    <Col span={8} offset={16} style={{textAlign: 'right', marginBottom: '5px'}}>
                        <Button type="primary" htmlType="submit" loading={loading}>查询</Button>
                        <Button style={{marginLeft: 8}} onClick={handleReset}>重置</Button>
                    </Col>
                </Row>
            </Form>
            <div className="dataArea">
                <div className="func">
                    <Button onClick={download}>导出</Button>
                </div>
                <Table
                    rowKey="id"
                    columns={columns}
                    dataSource={searchList}
                    scroll={{x: columns.length * 125}}
                    pagination={{
                        showQuickJumper: true,
                        total: searchList.length,
                        showSizeChanger: true
                    }}
                />
            </div>
            <Modal
                title="修改销售"
                visible={editVisible}
                onOk={handleOk}
                onCancel={handleCancel}
            >
                <Select
                    showSearch
                    value={saleName}
                    placeholder="销售名称"
                    defaultActiveFirstOption={false}
                    filterOption={false}
                    onSearch={nameSearch}
                    onChange={setSaleName}
                    style={{width: '180px'}}
                >
                    {
                        nameList.map(e => (
                            <Option key={e} value={e}>
                                {e}
                            </Option>
                        ))
                    }
                </Select>
            </Modal>
        </div>
    );
}

export default Form.create({name: 'roomList'})(withRouter(RoomList));
